package com.lenovo.leos.filebrowser.ui;

import java.util.HashMap;

import com.lenovo.leos.filebrowser.ui.FileIndex.Indexs;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

public class FileIndexProvider extends ContentProvider{
	
	 private static final String TAG = "FileIndexProvider";

     private static final String DATABASE_NAME = "file_index.db";
     private static final int DATABASE_VERSION = 3;
     private static final String INDEX_TABLE_NAME = "fileindex";
     
     private static HashMap<String, String> sIndexProjectionMap;

     private static final int INDEXS = 1;
     private static final int INDEX_ID = 2;
     private static final int DELETE_ID = 3;
     private static final int UPDATE_ID = 4;
     
     private static final UriMatcher sUriMatcher;
     
     /**
      * This class helps open, create, and upgrade the database file.
      */
     private static class DatabaseHelper extends SQLiteOpenHelper{

		public DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);			
		}
		
		 @Override
	        public void onCreate(SQLiteDatabase db) {
	            db.execSQL("CREATE TABLE " + INDEX_TABLE_NAME + " ("
	                    + Indexs._ID + " INTEGER PRIMARY KEY,"
	                    + Indexs.URI + " TEXT,"
	                    + Indexs.CPType + " TEXT,"
	                    + Indexs.COLUMN_NAME + " TEXT,"
	                    + Indexs.FULL_PATH + " TEXT"
	                    + ");");
	        }

	        @Override
	        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
	            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
	                    + newVersion + ", which will destroy all old data");
	            db.execSQL("DROP TABLE IF EXISTS fileindex");
	            onCreate(db);
	        }
    	 
     }
     
     private DatabaseHelper mOpenHelper;
     
     @Override
     public boolean onCreate() {
         mOpenHelper = new DatabaseHelper(getContext());
         return true;
     }

	@Override
	public int delete(Uri uri, String where, String[] whereArgs) {
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		int count = 0;
		
		switch (sUriMatcher.match(uri)) {
		case INDEXS:
            count = db.delete(INDEX_TABLE_NAME, where, whereArgs);
            break;

        case INDEX_ID:
            String indexId = uri.getPathSegments().get(1);
            
            count = db.delete(INDEX_TABLE_NAME, Indexs._ID + "=" + indexId
                    + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
            
            break;
        case DELETE_ID:
        	String wherearg = uri.getPathSegments().get(2);
        	        	
        	if(wherearg != null)
        	{
	        	String delSQL = "delete from "+ INDEX_TABLE_NAME +" where " + where + "=" 
	        	+"'"+ wherearg + "'";
	        	db.execSQL(delSQL );
        	}
            break;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
		}
		 getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}
	
	@Override
	public String getType(Uri uri) {
		switch (sUriMatcher.match(uri)) {
        case INDEXS:
            return Indexs.CONTENT_TYPE;

        case INDEX_ID:
            return Indexs.CONTENT_ITEM_TYPE;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
	}

	@Override
	public Uri insert(Uri uri, ContentValues initialValues) {
		// Validate the requested uri
		if (sUriMatcher.match(uri) != INDEXS) {
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
		ContentValues values;
        if (initialValues != null) {
            values = new ContentValues(initialValues);
        } else {
            values = new ContentValues();
        }
        
        // Make sure that the fields are all set
        if (values.containsKey(FileIndex.Indexs.URI) == false) {
            values.put(FileIndex.Indexs.URI, "");
        }

        if (values.containsKey(FileIndex.Indexs.CPType) == false) {
            values.put(FileIndex.Indexs.CPType, "");
        }

        if (values.containsKey(FileIndex.Indexs.COLUMN_NAME) == false) {
            Resources r = Resources.getSystem();
            values.put(FileIndex.Indexs.COLUMN_NAME, r.getString(android.R.string.untitled));
        }

        if (values.containsKey(FileIndex.Indexs.FULL_PATH) == false) {
            values.put(FileIndex.Indexs.FULL_PATH, "");
        }

        
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        long rowId = db.insert(INDEX_TABLE_NAME, Indexs.URI, values);
        if (rowId > 0) {
            Uri indexUri = ContentUris.withAppendedId(FileIndex.Indexs.CONTENT_URI, rowId);
            getContext().getContentResolver().notifyChange(indexUri, null);
            return indexUri;
        }

        throw new SQLException("Failed to insert row into " + uri);
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		
	 	SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

        switch (sUriMatcher.match(uri)) {
        case INDEXS:
            qb.setTables(INDEX_TABLE_NAME);
            qb.setProjectionMap(sIndexProjectionMap);
            break;

        case INDEX_ID:
            qb.setTables(INDEX_TABLE_NAME);
            qb.setProjectionMap(sIndexProjectionMap);
            qb.appendWhere(Indexs._ID + "=" + uri.getPathSegments().get(1));
            break;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);	        
        }
        
        // If no sort order is specified use the default
        String orderBy;
        if (TextUtils.isEmpty(sortOrder)) {
            orderBy = FileIndex.Indexs.DEFAULT_SORT_ORDER;
        } else {
            orderBy = sortOrder;
        }
        
        // Get the database and run the query
        SQLiteDatabase db = mOpenHelper.getReadableDatabase();
        Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy);

        // Tell the cursor what uri to watch, so it knows when its source data changes
        c.setNotificationUri(getContext().getContentResolver(), uri);
        return c;		
	}

	@Override
	public int update(Uri uri, ContentValues values, String where,
			String[] whereArgs) {
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		int count;
		switch (sUriMatcher.match(uri)) {
        case INDEXS:
            count = db.update(INDEX_TABLE_NAME, values, where, whereArgs);
            break;

        case INDEX_ID:
            String indexId = uri.getPathSegments().get(1);
            count = db.update(INDEX_TABLE_NAME, values, Indexs._ID + "=" + indexId
                    + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
            break;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return count;
	}
	
	static {
        sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        sUriMatcher.addURI(FileIndex.AUTHORITY, "fileindex", INDEXS);
        sUriMatcher.addURI(FileIndex.AUTHORITY, "fileindex/#", INDEX_ID);
        sUriMatcher.addURI(FileIndex.AUTHORITY, "fileindex/delete/*", DELETE_ID);
        sUriMatcher.addURI(FileIndex.AUTHORITY, "fileindex/update/uri/*/filepath/*", UPDATE_ID);

        sIndexProjectionMap = new HashMap<String, String>();
        sIndexProjectionMap.put(Indexs._ID, Indexs._ID);
        sIndexProjectionMap.put(Indexs.URI, Indexs.URI);
        sIndexProjectionMap.put(Indexs.CPType, Indexs.CPType);
        sIndexProjectionMap.put(Indexs.COLUMN_NAME, Indexs.COLUMN_NAME);
        sIndexProjectionMap.put(Indexs.FULL_PATH, Indexs.FULL_PATH);
    }

}
